<template>
  <BKModal
    v-model="visible"
    title="已保存信息"
    width="70%"
    height="80%"
    transfer
  >
    <BKForm
      :items="conditions"
      ref="conditionForm"
      class="condition-form"
      inline
      label-width="auto"
      button-size="mini"
      submit-text="查询"
      submit-icon="ri-search-line"
      reset-icon="ri-brush-3-line"
      @submit="search"
      @reset="reset"
      size="mini"
    />
    <ConfigGrid
      ref="grid"
      :configs="configs"
      :has-add="false"
      :has-batch-remove="false"
      :before-query="beforeQuery"
      @conditionLoaded="conditionLoaded"
      is-external-condition
    >
      <template #toolbarLeftPrepend="{rows}">
        <el-button
          size="mini"
          type="danger"
          @click="batchRemove(rows)"
          :disabled="!rows.length"
        >
          批量删除
        </el-button>
      </template>
    </ConfigGrid>
  </BKModal>
</template>

<script>
export default {
  name: 'SaveRecords',
  props: {
    metaSet: {
      type: String,
      default: ''
    },
    idKey: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      visible: false,
      unit: 'min',
      ls: '',
      keywords: '',
      conditions: []
    }
  },
  computed: {
    configs () {
      return {
        isView: false,
        appId: 'YSJC',
        bzCode: 'YSJC',
        metaSet: this.metaSet,
        noOperation: true,
        afterFetchColumns: this.afterFetchColumns,
        gridMethod: 'selectCxq',
        module: '数据',
        customExportMethod: this.customExportMethod
      }
    }
  },
  methods: {
    open () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.grid.refreshList({})
      })
    },
    afterFetchColumns (columns) {
      for (const item of columns) {
        if (item.field === 'LS') {
          if (this.metaSet === 'YSQJC_BYTJ_RYLSCXQ') {
            item.formatter = ({ row }) => row.LS + (row.LSDW || '')
          } else {
            item.formatter = ({ row }) => row.LS_TEXT
          }
        }
      }
      columns.push({
        title: '操作',
        fixed: 'right',
        width: 150,
        slots: {
          default: ({ row }) => {
            return [
              <el-button size="mini" type="primary" onClick={() => this.choose(row)}>选择</el-button>,
              <el-button size="mini" type="danger" onClick={() => this.remove(row)}>删除</el-button>
            ]
          }
        }
      })
      return columns
    },
    choose (row) {
      this.$emit('change', row)
      this.visible = false
    },
    remove (row) {
      this.$confirm('请确认是否删除此条数据？', '提示', { type: 'warning' }).then(async () => {
        await this.$request.post('/ysjc/bytjjs/deleteBcXx', {
          TABLE_NAME: this.metaSet,
          ID: row[this.idKey]
        })
        this.$refs.grid.refresh()
      })
    },
    batchRemove (rows) {
      this.$confirm('请确认是否删除选中的数据？', '提示', { type: 'warning' }).then(async () => {
        await this.$request.post('/ysjc/bytjjs/deleteBcXx', {
          TABLE_NAME: this.metaSet,
          ID: rows.map(item => item[this.idKey]).join(',')
        })
        this.$refs.grid.refresh()
      })
    },
    conditionLoaded (conditions) {
      for (const item of conditions) {
        if (item.field === 'STNM') {
          item.slot = () => {
            return [
              <BKInput vModel={this.keywords} size="mini"></BKInput>
            ]
          }
        }
        if (item.field === 'LS') {
          console.log(item.props)
          if (this.metaSet === 'YSQJC_BYTJ_RYLSCXQ') {
            item.slot = () => {
              return [
                <BKInput
                  vModel={this.ls}
                  size="mini"
                  is-number
                  class="has-select"
                  digits={2}
                >
                  <template slot="append">
                    <BKSelect
                      size="mini"
                      vModel={this.unit}
                      dictionaryKey="YSQJC_JC_LSDW"
                      clearable={false}
                    />
                  </template>
                </BKInput>
              ]
            }
          } else {
            item.slot = () => {
              return [
                <BKSelect vModel={this.ls} size="mini" dictionaryKey={item.props.dictionaryKey}></BKSelect>
              ]
            }
          }
        }
      }
      this.conditions = conditions
      this.$refs.grid.connectCoditionForm(this.$refs.conditionForm)
    },
    beforeQuery (params) {
      const obj = {}
      if (this.metaSet === 'YSQJC_BYTJ_RYLSCXQ') {
        obj.LS = this.ls.toString()
        if (this.ls) {
          obj.LSDW = this.unit
        }
      } else {
        obj.LS = this.ls
      }
      obj.STCD = this.keywords
      params.methodParams = obj
      this.$refs.grid.currentQueryParams = params
      return params
    },
    search () {
      this.$refs.grid.refreshList({})
    },
    reset () {
      this.keywords = ''
      this.ls = ''
      this.unit = 'min'
      this.search()
    },
    async customExportMethod (params) {
      this.$refs.grid.exporting = true
      const tableColumns = this.$refs.grid.$refs.table.getTableColumn().tableColumn
      const metaWidthMap = {}
      for (const c of tableColumns) {
        if (!c.property) continue
        metaWidthMap[c.property] = c.renderWidth
      }
      metaWidthMap.XH = 80
      const { data, fileName } = await this.$request.getFileStreamByPost('/grid/export', {
        excelTitle: this.configs.module,
        ...params,
        metaSet: params.metaSet + '_DC',
        metaWidthMap: JSON.stringify(metaWidthMap)
      })
      this.$refs.grid.exporting = false
      this.$request.downloadBlobFile(data, fileName)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .bk-form-wrapper.condition-form .el-select {
  width: unset !important;
}

::v-deep .condition-form {
  height: auto;
  margin-top: 10px;

  .el-form {
    padding: 0 10px;

    .el-form-item {
      margin-bottom: 0;
    }
  }

  .form-buttons {
    padding: 0;
    border: none;
    justify-content: flex-start;
    flex-direction: row-reverse;
    margin: 0;

    .el-button {
      display: flex;
      align-items: center;
      justify-content: center;

      > i {
        margin-right: 6px;
      }
    }
  }
}
</style>
